<template>
  <a-card class="general-card" title="搜索热词" :bordered="false">
    <a-tabs
      :default-active-key="hotWordsFormData.hotWordsTab"
      @change="clickHotWords"
    >
      <a-tab-pane key="todayHotWords" title="今日热词">
        <a-col :span="16" style="margin-bottom: 10px">
          <a-space>
            <a-button type="primary" @click="addHotWords"
              >设置今日热词</a-button
            >
          </a-space>
        </a-col>
        <a-col>
          <a-space>
            <a-alert type="success" :show-icon="false">
              这里展示今日系统中搜索前一百的搜索热词，分数为热词在排序系统中的分数，分数越高，可以在用户获取热词时进行优先展示（首页商品搜索栏下方推荐位）（分数可以填写负数，会降低推荐度）
            </a-alert>
          </a-space>
        </a-col>
        <a-col style="margin: 20px 0">
          <a-space :key="update" size="medium">
            <a-tag
              v-for="item of hotWordsFormData.hotWordsList"
              :key="item"
              size="large"
              closable
              visible="true"
              @close="handleRemoveHotWords(item.value)"
              >{{ item.value }}</a-tag
            >
          </a-space>
        </a-col>
      </a-tab-pane>
      <a-tab-pane key="historyHotWords" title="历史热词">
        <a-col :span="16" style="margin-bottom: 10px">
          <a-space>
            <a-date-picker
              v-model="hotWordsFormData.date"
              :disabled-date="disabledDate"
              style="width: 200px"
              placeholder="选择查看日期"
              @change="changePicker"
            />
          </a-space>
        </a-col>
        <a-col>
          <a-space>
            <a-alert type="success" :show-icon="false">
              这里展示历史某一天的热词数据统计，可根据需求配置每日持久化多少条数据。
            </a-alert>
          </a-space>
        </a-col>
        <a-col :span="16"><div id="hotWordsChart"></div></a-col>
      </a-tab-pane>
      <a-tab-pane key="statisticsHotWords" title="热词统计">
        <a-col>
          <recent-time
            :date-type="defaultDateType.date"
            @on-change="handleClickTimeChange"
          ></recent-time>
          <a-input-number
            v-model="hotWordsFormData.statisticsDate.top"
            :style="{ width: '70px', marginLeft: '10px' }"
            :min="10"
            :max="50"
            class="input-demo"
            @change="topChange"
          />
        </a-col>
        <a-col><div id="statisticsHotWordsChart"></div></a-col>
        <a-col>
          <PickTablePage
            ref="tablePageRef"
            :columns="columnsTable"
            :api="getHotWordsStatistics"
            :api-params="hotWordsFormData.statisticsDate"
          ></PickTablePage>
        </a-col>
      </a-tab-pane>
      <a-tab-pane key="setupHotWords" title="设置热词">
        <a-form
          ref="hotWordFormRef"
          :model="hotWordsFormData.hotWordForm"
          :style="{ width: '100%' }"
          layout="horizontal"
          auto-label-width
        >
          <a-form-item
            field="hotWordsSettingItems"
            label="热词默认配置"
            :rules="[REQUIRED]"
          >
            <div
              v-for="(item, index) in hotWordsFormData.hotWordForm
                .hotWordsSettingItems"
              :key="index"
              class="item-label"
            >
              <div>
                <div class="item-keyword">
                  <div>热词：</div
                  ><a-input
                    v-model="item.keywords"
                    type="text"
                    placeholder="请填写热词"
                  />
                </div>
                <div class="item-score">
                  <div>分数：</div
                  ><a-input-number v-model="item.score" :min="0" :max="5" />
                </div>
              </div>
              <div
                ><a-button
                  type="primary"
                  @click="
                    hotWordsFormData.hotWordForm.hotWordsSettingItems.splice(
                      index,
                      1
                    )
                  "
                  >删除</a-button
                ></div
              >
            </div>
            <a-button @click="addSetItem">添加配置</a-button>
          </a-form-item>
          <a-form-item
            field="saveNum"
            label="每日持久化热词数量"
            :rules="[REQUIRED]"
          >
            <a-input-number
              v-model="hotWordsFormData.hotWordForm.saveNum"
              :min="0"
              :style="{ width: '88px' }"
            />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="hotWordFormSubmit()"
              >保存</a-button
            >
          </a-form-item>
        </a-form>
      </a-tab-pane>
    </a-tabs>
    <!--设置今日热词-->
    <a-modal
      v-model:visible="hotWordsFormData.enableAddModal"
      :align-center="false"
      :footer="false"
    >
      <template #title>设置热词</template>
      <a-form
        ref="formRef"
        :model="hotWordsFormData.form"
        @submit="addHotWordsOk"
      >
        <a-form-item
          field="keywords"
          label="热词"
          :rules="[REQUIRED, VARCHAR20]"
          :validate-trigger="['change']"
        >
          <a-input v-model="hotWordsFormData.form.keywords" />
        </a-form-item>
        <a-form-item
          field="points"
          label="分数"
          :rules="[REQUIRED]"
          :validate-trigger="['change']"
        >
          <a-input v-model="hotWordsFormData.form.points" />
        </a-form-item>
        <a-form-item label="操作">
          <a-button :loading="hotWordsFormData.formLoading" html-type="submit"
          type="primary">保存</a-button
          >
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script setup lang="ts">
  import {
deleteHotWords,
getHotWords,
getHotWordsHistory,
getHotWordsStatistics,
getSetting,
setHotWords,
setSetting,
} from '@/api/index';
import recentTime from '@/components/recent-time/index.vue';
import { PickTablePage } from '@pickmall/ui-v3-components'
import { defaultDateType, handleClickTimeChange } from '@/hooks/statistics';
import { ColumnsDataRule } from '@/types/global';
import { unixToDate } from '@/utils/filters';
import { REQUIRED, VARCHAR20 } from '@/utils/validator';
import { Chart } from '@antv/g2';
import { Message } from '@arco-design/web-vue';
import { FormInstance } from '@arco-design/web-vue/es/form';
import { onMounted, reactive, ref, watch } from 'vue';
import useCurrentInstance from '@/hooks/useCurrentInstance';

  //  获取modal
  const modal = useCurrentInstance().globalProperties?.$modal;
  const formRef = ref<FormInstance>();
  const hotWordFormRef = ref<FormInstance>();
  // 获取modal
  // const modal = useCurrentInstance().globalProperties?.$modal;
  const update = ref('');
  const tablePageRef = ref<any>();
  interface formInterface {
    enableAddModal: boolean;
    formLoading: boolean;
    form: {
      keywords: string;
      point: string;
      [key:string]: any;
    };
    hotWordsList: Array<any>;
    update: boolean;
    date: any;
    hotWordsData: Array<any>;
    hotWordsChart: any;
    hotWordsTab: string;
    statisticsDate: any;
    statisticsHotWordsData: Array<any>;
    statisticsHotWordsChart: any;
    hotWordForm: any;
    [key:string]: any;
  }
  // 数据集
  const hotWordsFormData: formInterface = reactive<any>({
    enableAddModal: false,
    formLoading: false,
    // 添加热词表单提交数据
    form: {
      keywords: '',
      points: '',
    },
    hotWordsList: [],
    update: false,
    // 默认当天
    date: unixToDate(new Date().getTime() / 1000 - 24 * 60 * 60, 'yyyy-MM-dd'),
    // 历史热词数据
    hotWordsData: [],
    // 图表
    hotWordsChart: '',
    // 当前热词tab栏
    hotWordsTab: 'todayHotWords',
    // 热词统计图表入参
    statisticsDate: {
      searchType: defaultDateType.date.recent,
      year: defaultDateType.date.month || new Date().getFullYear(),
      month: '',
      top: 50,
    },
    // 热词统计数据
    statisticsHotWordsData: [],
    // 热词统计图表
    statisticsHotWordsChart: '',
    hotWordForm: {
      saveNum: 1, // 每日保存数量
      // 热词默认配置
      hotWordsSettingItems: [{ keywords: '', score: 1 }],
    },
  });
  const columnsTable: ColumnsDataRule[] = [
    { title: '热词名称', dataIndex: 'keywords' },
    { title: '搜索次数', dataIndex: 'score' },
  ];
  // 获取今日热词
  const getHotWordsList = () => {
    getHotWords().then((res: any) => {
      hotWordsFormData.hotWordsList = res.data.result;
      hotWordsFormData.update = !hotWordsFormData.update;
    });
  };
  // 显示今日热词弹框
  const addHotWords = (mp: any) => {
    hotWordsFormData.enableAddModal = true;
    Object.keys(hotWordsFormData.form).forEach((key) => {
      hotWordsFormData.form[key] = '';
    });
  };
  // 设置今日热词
  async function addHotWordsOk() {
    const auth = await formRef.value?.validate();
    if (!auth) {
      const res = await setHotWords(hotWordsFormData.form);
      if (res.data.success) {
        Message.success('添加成功！');
        hotWordsFormData.enableAddModal = false;
        getHotWordsList();
      }
    }
  }
  // 删除今日热词
  const handleRemoveHotWords = (words: string) => {
    console.log('删除');
    modal.confirm({
      title: '确认删除',
      content: `您确认要删除此当前热词?`,
      alignCenter: false,
      onOk: async () => {
        deleteHotWords({ words }).then((res) => {
          if (res.data.success) {
            Message.success('删除成功！');
            getHotWordsList();
          }
        });
      },
    });
  };
  // 加载图表（历史热词）
  const chart = () => {
    const data = hotWordsFormData.hotWordsData;
    hotWordsFormData.hotWordsChart.data(data);
    hotWordsFormData.hotWordsChart.tooltip({
      showCrosshairs: true,
      shared: true,
    });
    hotWordsFormData.hotWordsChart
      .interval()
      .position('keywords*score')
      .color('#f59b99');
    hotWordsFormData.hotWordsChart.render();
  };
  // 初始化图表（历史热词）
  const search = async (date: any) => {
    const res = await getHotWordsHistory({ date });
    if (res.data.success) {
      hotWordsFormData.hotWordsData = res.data.result;
    }
    if (!hotWordsFormData.hotWordsChart) {
      hotWordsFormData.hotWordsChart = new Chart({
        container: 'hotWordsChart',
        autoFit: true,
        height: 500,
        padding: [50, 50, 50, 50],
      });
    }
    chart();
  };
  // 选择日期
  const changePicker = (dateString: any, date: any) => {
    search(dateString);
  };
  // 日期可选范围
  const disabledDate = (current: any) => {
    return new Date(current).getTime() / 1000 > new Date().getTime() / 1000;
  };
  // 加载图表（热词统计）
  const statisticsChart = () => {
    const data = hotWordsFormData.statisticsHotWordsData;
    hotWordsFormData.statisticsHotWordsChart.data(data);
    hotWordsFormData.statisticsHotWordsChart.tooltip({
      showCrosshairs: true,
      shared: true,
    });
    hotWordsFormData.statisticsHotWordsChart
      .interval()
      .position('keywords*score')
      .color('#f59b99');
    hotWordsFormData.statisticsHotWordsChart.render();
  };
  // 初始化图表（热词统计）
  const getHotWordsStatisticsList = async (params: any) => {
    const res = await getHotWordsStatistics(params);
    if (res.data.success) {
      hotWordsFormData.statisticsHotWordsData = res.data.result;
      tablePageRef.value.init();
    }
    if (!hotWordsFormData.statisticsHotWordsChart) {
      hotWordsFormData.statisticsHotWordsChart = new Chart({
        container: 'statisticsHotWordsChart',
        autoFit: true,
        height: 500,
        padding: [50, 50, 50, 50],
      });
    }
    statisticsChart();
  };
  // top值改变
  const topChange = (val: number | undefined, event: any): any => {
    hotWordsFormData.statisticsDate.top = val;
    getHotWordsStatisticsList(hotWordsFormData.statisticsDate);
  };
  // 获取热词
  const init = async () => {
    const res = await getSetting('HOT_WORDS');
    // hotWordsFormData.hotWordForm = {
    //     hotWordsSettingItems:[{keywords: "格拉特", score: 0},{keywords: "啦啦啦", score: 1}],
    //     saveNum:1
    // }
    if (res.data.success) {
      hotWordsFormData.hotWordForm = res.data.result;
    }
  };
  // 添加热词默认配置
  const addSetItem = () => {
    if (hotWordsFormData.hotWordForm.hotWordsSettingItems.length >= 5) {
      Message.error('最多5个热词项！');
    } else {
      hotWordsFormData.hotWordForm.hotWordsSettingItems.push({
        keywords: '',
        score: 1,
      });
    }
  };
  // 设置热词
  const hotWordFormSubmit = async () => {
    const auth = await hotWordFormRef.value?.validate();
    if (!auth) {
      const res = await setSetting('HOT_WORDS', hotWordsFormData.hotWordForm);
      if (res.data.success) {
        Message.success('设置成功！');
        init();
      }
    }
  };
  // 搜索热词tab栏切换
  const clickHotWords = (name: any) => {
    hotWordsFormData.hotWordsTab = name;
    if (name == 'todayHotWords') {
      console.log('今日热词');
      getHotWordsList();
    } else if (name == 'historyHotWords') {
      console.log('历史热词');
      search(hotWordsFormData.date);
    } else if (name == 'statisticsHotWords') {
      console.log('热词统计');
      getHotWordsStatisticsList(hotWordsFormData.statisticsDate);
    } else if (name == 'setupHotWords') {
      console.log('设置热词');
      init();
    }
  };
  // 初始化
  onMounted(() => {
    // 获取今日热词
    getHotWordsList();
    // 获取历史热词
    // search(hotWordsFormData.date);
    // 获取热词统计
    // getHotWordsStatisticsList(hotWordsFormData.statisticsDate);
    // 获取设置热词数据
    // init();
  });
  // 监听值的改变
  watch(
    () => defaultDateType.date,
    (val) => {
      hotWordsFormData.statisticsDate.searchType = val.recent;
      if (val.month) {
        // eslint-disable-next-line prefer-destructuring,no-nested-ternary
        hotWordsFormData.statisticsDate.month = val.month.split('-')[1]
          ? val.month.split('-')[1].indexOf('0') != -1
            ? val.month.split('-')[1].substr(1)
            : ''
          : '';
        // eslint-disable-next-line prefer-destructuring
        hotWordsFormData.statisticsDate.year = val.month.split('-')[0];
      }
      getHotWordsStatisticsList(hotWordsFormData.statisticsDate);
    },
    { deep: true, immediate: true }
  );
</script>

<style scoped lang="less">
  #hotWordsChart {
    width: 100% !important;
  }
  .breadcrumb {
    display: flex;
    align-items: center;
    padding-left: 15px;
    height: 40px;
    > span {
      margin-right: 15px;
      cursor: pointer;
    }
  }
  .active {
    color: #165dff;
    position: relative;
  }
  .active:before {
    content: '';
    position: absolute;
    bottom: -10px;
    left: 0;
    width: 100%;
    height: 3px;
    background: #165dff;
  }

  :deep(.arco-form-item-content) {
    display: block;
  }
  .item-label {
    border-bottom: 1px solid #ededed;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    width: 500px;
    justify-content: space-between;
  }
  .item-keyword,
  .item-score {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    > div {
      width: 80px;
      /*margin-right: 20px;*/
    }
  }
</style>
